package com.stoneframe.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.stoneframe.controller.base.BaseController;
import com.stoneframe.service.LoginService;
import com.stoneframe.util.baseApp.AppHelper;
import com.stoneframe.util.baseApp.Const;
import com.stoneframe.util.baseApp.ConstMessage;
import com.stoneframe.util.baseApp.PageData;
import com.stoneframe.util.baseApp.ToolHelper;
import com.stoneframe.util.baseDate.DateHelper;

@Controller
public class LoginController extends BaseController {
	
	private String controllerName="LoginController.";
	
	@Resource(name="loginService")
	private LoginService loginService;
	
	/**
	 * 跳转登录页面 
	 */
	@RequestMapping(value="login_toLogin")
	public ModelAndView toLogin(){
		logBefore(logger, controllerName+"toLogin");
		
		ModelAndView mv=this.getModelAndView();
		PageData pd=this.getPageData();
		
		pd.put("sysName", ToolHelper.readFile(Const.SysName));
		mv.setViewName("login");
		mv.addObject("pd",pd);
		
		logAfter(logger);
		return mv;
	}
	
	/**
	 * 登录 
	 */
	@RequestMapping(value="login_login",produces="application/json;charset=UTF-8")
	@ResponseBody
	public Object login() throws Exception{
		logBefore(logger, controllerName+"login");
		
		Map<String,Object> map=new HashMap<String,Object>();
		PageData pd=this.getPageData();
		String errInfo="success";
		
		String keyData[]=pd.getString("keyData").split(",stone,");
		if(null!=keyData&&keyData.length==3){
			Subject currentUser=SecurityUtils.getSubject();
			Session session=currentUser.getSession();
			String sessionCode=(String)session.getAttribute(Const.SessionSecurityCode);
			String code=keyData[2];
			if(ToolHelper.isEmpty(code)){
				errInfo=ConstMessage.NullCode;
			}else{
				String userName=keyData[0];
				String userPwd=keyData[1];
				if(ToolHelper.notEmpty(sessionCode)&&sessionCode.equalsIgnoreCase(code)){
					String passwd=new SimpleHash("SHA-1",userName,userPwd).toString();
					pd.put("userName", userName);
					pd.put("userPwd", passwd);
					pd=loginService.getUserByNameAndPwd(pd);
					if(null!=pd){
						pd.put("lastLogin", DateHelper.getTime().toString());
						pd.put("lastAddress",getRemoteAddress());
						loginService.updateLastLogin(pd);
						session.setAttribute(Const.SessionUser, pd);
						session.removeAttribute(Const.SessionSecurityCode);
						Subject subject=SecurityUtils.getSubject();
						UsernamePasswordToken token=new UsernamePasswordToken(userName,userPwd);
						try{
							subject.login(token);
						}catch(AuthenticationException e){
							errInfo=ConstMessage.AuthenticationFailed;
						}
					}else{
						errInfo=ConstMessage.UserError;
					}
				}else{
					errInfo=ConstMessage.CodeError;
				}
			}
		}else{
			errInfo=ConstMessage.MissPara;
		}
		map.put("result", errInfo);
		
		logAfter(logger);
		return AppHelper.returnObject(pd, map);
	}
	
	/**
	 * 获取登录用户的IP 
	 */
	private String getRemoteAddress(){
		String address="";
		try{
			HttpServletRequest request=this.getRequest();
			if(request.getHeader("x-forwarded-for")==null){
				address=request.getRemoteAddr();
			}else{
				address=request.getHeader("x-forwarded-for");
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}
		return address;
	}
	
	/**
	 * 注销
	 */
	@RequestMapping(value="logout")
	public ModelAndView logout(){
		logBefore(logger, controllerName+"logout");
		ModelAndView mv=this.getModelAndView();
		PageData pd=this.getPageData();
		Subject currentUser=SecurityUtils.getSubject();
		Session session=currentUser.getSession();
		session.removeAttribute(Const.SessionUser);
		session.removeAttribute(Const.SessionUserName);
		currentUser.logout();
		pd.put("SysName",ToolHelper.readFile(Const.SysName));
		mv.setViewName("login");
		mv.addObject("pd",pd);
		
		logAfter(logger);
		return mv;
	}
	
	/**
	 * 获取当前用户信息
	 */
	@RequestMapping(value="getUserInfo")
	@ResponseBody
	public Object getUserInfo(){
		logBefore(logger, controllerName+"getCurrentUser");
		
		PageData pd=this.getPageData();
		Map<String,Object> map=new HashMap();
		map.put("userInfo", this.getCurrentUser());
		map.put("result", "0");
		map.put("msg", "获取成功");
		
		logAfter(logger);
		return AppHelper.returnObject(pd, map);
	}

}
